package com.xiangsai;

/**
 * @program: paxos-java-demo
 * @description
 * @author: wzx
 * @create: 2021-07-09 16:41
 **/
public class Acceptor {

    private AcceptorStatus status = AcceptorStatus.NONE;
    private Proposal promisedProposal = new Proposal();

    //提案准备
    public PrepareResult onPrepare(Proposal proposal) {
        PrepareResult result = new PrepareResult();
        //假设50%失败概率
        if (Math.random() > 0.5) {
            Utils.printStr("网络错误:" + proposal.toString());
            return null;
        }

        switch (status) {
            case NONE: //表示之前没有承诺过任何提案者
                result.setAcceptorStatus(AcceptorStatus.NONE);
                result.setPromised(true);
                result.setProposal(null);
                status = AcceptorStatus.PROMISED; //修改自身，接受提案
                promisedProposal.copyFromInstance(proposal); //已经接受的提案就是本次的提案
                return result;
            case PROMISED: //已经承诺过任意提案者
                //判断先后顺序,只承诺较新的提案
                if (promisedProposal.getId() > proposal.getId()) {
                    result.setPromised(false);
                } else {
                    result.setPromised(true);
                }
                result.setAcceptorStatus(AcceptorStatus.PROMISED);
                result.setProposal(promisedProposal);
                return result;
            default:
                return null;
        }
    }
}
